package com.gj.springbootrabbitmq.controller;

import com.gj.springbootrabbitmq.config.MyCallBack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

@RestController
@RequestMapping("/confirm")
@Slf4j
public class ProducerController {
    public static final String CONFIRM_EXCHANGE_NAME = "confirm.exchange";
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MyCallBack myCallBack;
    // 依赖注入 rabbitTemplate 之后再设置它的回调对象
    @PostConstruct
    public void init(){
        //把回调对象（含有回调函数）通过set注入到rabbitTemplate，rabbitTemplate的内部接口需要注入
        rabbitTemplate.setConfirmCallback(myCallBack);

        /**
         * true ：
         * 交换机无法将消息进行路由时，会将该消息返回给生产者
         * false ：
         * 如果发现消息无法进行路由，则直接丢弃
         */
        rabbitTemplate.setMandatory(true);
        // 设置回退消息交给谁处理
        rabbitTemplate.setReturnCallback(myCallBack);
    }
    @GetMapping("sendMessage/{message}")
    public void sendMessage(@PathVariable String message){
        // 指定消息 id 为 1
        CorrelationData correlationData1=new CorrelationData("1");//这里有消息id和消息相关内容
        String routingKey="key1";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routingKey,message+routingKey,correlationData1);

        //没有这个routingkey,测试这种情况
        CorrelationData correlationData2=new CorrelationData("2");
        routingKey="key2";
        rabbitTemplate.convertAndSend(CONFIRM_EXCHANGE_NAME,routingKey,message+routingKey,correlationData2);

        log.info(" send message is:{}",message);
    }
}

